import React, { useEffect, useRef, useState } from "react";
import styles from "./index.module.less"
import NoteItem from "../../components/NoteItem";
import { Modal } from 'antd';
import NoteContent from "../../components/NoteContent";
import { MyIcon } from "../../Icon/MyIcon";
import request from "../../server/request";
import debounce from "../../utils/debounce";

interface noteCard {
  id: string,
  user_id: string,
  title: string,
  cover_image: string,
  liked: boolean,
  likedCount: number,
  userInfo: {
    nickName: string,
    avatar: string
  }
}

const H1 = 266, H2 = 150;

let topArr: number[] = [0, 0, 0, 0, 0];

let renderIndex = [0, 20];

const Main: React.FC = () => {

  // 详情弹窗
  const [curData, setaCurData] = useState<noteCard>({
    id: '',
    user_id: '',
    title: '',
    cover_image: '',
    liked: false,
    likedCount: 0,
    userInfo: {
      nickName: '',
      avatar: ''
    }
  }); // 当前详情数据
  const [isModalOpen, setIsModalOpen] = useState(false); // 详情弹框
  // 关闭弹窗
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  //查看详细笔记
  const showDetail = (item: any) => {
    setaCurData(item);
    setIsModalOpen(true);
  };



  // 列表
  const [arr, setArr] = useState<any[]>([]); // 列表数据
  const [renderArr, setRenderArr] = useState<any[]>([]); //渲染列表
  const [page, setPage] = useState(1); // 列表页数
  const [hasNextPage, setHasNextPage] = useState(true); // 列表是否有下一页
  const [column, setColumn] = useState(5); // 列表行数
  const pageRef = useRef<HTMLDivElement>(null);
  const scrollYRef = useRef<number>(0);

  useEffect(() => {
    // 初始化
    getInitData();
    return () => {
      topArr = [0, 0, 0, 0, 0];
      renderIndex = [0, 20]
    }
  }, []);

  useEffect(() => {
    window.addEventListener('scroll',slideRender);
    return () => {
      window.removeEventListener('scroll',slideRender);
    }
  },[scrollY]);

  useEffect(() => {
    // 监听滚动
    document.addEventListener('scroll', loadNext);
    setRenderArr(arr.slice(renderIndex[0], renderIndex[1]));
    return () => {
      document.removeEventListener("scroll", loadNext);
    }
  }, [arr]);

  const requestData = async (page: number, id?: number) => {
    const cardWidth = 240, leftMargin = 42, topMargin = 88;
    const res = await request('/note_list', { page, my_id: id }) as any;
    const { resultList, hasNextPage } = res;
    const newArr = [...arr, ...resultList];
    for (let i = arr.length; i < newArr.length; i++) {
      newArr[i].left = (i % column) * cardWidth + leftMargin;
      newArr[i].top = getTop(i, newArr[i].cover_image) + topMargin;
    }
    setArr(newArr);
    setHasNextPage(hasNextPage);
  }

  const debounceRequest = debounce(requestData,500);

  // 获取初始化数据
  const getInitData = () => {
    const my_id = Number(localStorage.getItem('userId'));
    requestData(page,my_id)
    // request('/note_list', { page, my_id }).then((res: any) => {
    //   const { resultList, hasNextPage } = res;
    //   for (let i = 0; i < resultList.length; i++) {
    //     resultList[i].left = (i % column) * width + leftMargin;
    //     resultList[i].top = getTop(i, resultList[i].cover_image) + topMargin;
    //   }
    //   setArr(resultList);
    //   setHasNextPage(hasNextPage);
    // });
  }
  // 滚动加载
  const loadNext = () => {
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    if (!hasNextPage) return;
    const clientHeight = document.documentElement.clientHeight;
    const scrollHeight = document.documentElement.scrollHeight;
    if (scrollTop + clientHeight + 600 >= scrollHeight) {
     debounceRequest(page + 1);
     setPage(page + 1);
      // request('/note_list', { page: page + 1 }).then((res: any) => {
      //   const { resultList, hasNextPage } = res;
      //   setHasNextPage(hasNextPage);
      //   const newArr = [...arr, ...resultList];
      //   for (let i = arr.length; i < newArr.length; i++) {
      //     newArr[i].left = (i % column) * width + leftMargin;
      //     newArr[i].top = getTop(i, newArr[i].cover_image) + topMargin;
      //   }
      //   setArr(newArr);
      //   setPage(page + 1);
      // });
    }
  }
  // const getTop = (i: number, col: number, item: noteCard) => {
  //   const top = topArr[col];
  //   const img = new Image();
  //   img.src = item.cover_image;
  //   const aspectRatio = img.naturalWidth / img.naturalHeight;
  //   topArr[col] += (aspectRatio < 1 ? H1 : H2) + 100;
  //   heightArr[i] = top;
  //   return top;
  // }
  // 列表元素位置
  const getTop = (i: number, src: string) => {
    let topIndex = 0;
    if (i < column) {
      topIndex = i;
    }
    else {
      switch ((i + 1) % column) {
        case 0:
          topIndex = column - 1;
          break;
        default:
          topIndex = ((i + 1)% column) - 1;
          break;
      }
    }
    const top = topArr[topIndex];
    const ratio = src.match(/ratio=([\d\.]+)/)?.[1] || 0.5;
    topArr[topIndex] += (Number(ratio) < 1 ? H1 : H2) + 100;    
    return top;
  }

  // 渲染数组 滑动渲染
  const slideRender = () => {
    let [ startIndex, endIndex ] = renderIndex;
    if(window.scrollY - scrollYRef.current  > 300 && window.scrollY > 400) {
          scrollYRef.current = window.scrollY;
          renderIndex = [startIndex + 5, endIndex + 5]
          
    } else if(window.scrollY - scrollYRef.current  < -200 && window.scrollY > 200){
      scrollYRef.current = window.scrollY;
      if(startIndex - 5 < 0) {
        renderIndex = [0, 20]
      }
      else {
        renderIndex = [startIndex - 5, endIndex - 5];
      }

    }
    // 渲染数组
    setRenderArr([...arr.slice(renderIndex[0], renderIndex[1])]);
    
  }

  return (
    <>
      <div className={styles['feeds-page']} ref={pageRef} >
        {renderArr.map((item, i) => {
          return <div style={{
            position: "absolute",
            top:item.top,
            left:item.left
          }}
            key={item.id}
          >
            <NoteItem key={item.id + Math.random()} item={item} showDetail={() => showDetail(item)} />
          </div>

        })}
      </div>
      {
        isModalOpen
          ? (
            <Modal
              maskStyle={{ backgroundColor: 'hsla(0,0%,97.6%,.98)' }}
              title={null} open={isModalOpen}
              onCancel={handleCancel}
              footer={null}
              width={800}
              wrapClassName={styles['main-modal']}
            >

              <NoteContent data={curData} />
            </Modal>
          )
          : null
      }


    </>
  );
};

export default Main;